package com.lu.dao.impl;

import com.lu.dao.BaseDao;
import com.lu.dao.UserDao;
import com.lu.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl extends BaseDao implements UserDao {
    @Override
    public User getOneUser(int uid) {
        User user = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "select UId,UName,UPassword,UType from User where UId = ?";
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1,uid);
            rs = pstmt.executeQuery();
            if(rs.next()){
                String uname = rs.getString("UName");
                String upassword = rs.getString("UPassword");
                int utype = rs.getInt("UType");
                user = new User(uid,uname,upassword,utype);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con,pstmt,rs);
        }
        return user;
    }

    @Override
    public User getOneUser(String uname, String upassword) {
        User user = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "select UId,UName,UPassword,UType from User where UName = ? and UPassword = ?";
        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1,uname);
            pstmt.setString(2,upassword);
            rs = pstmt.executeQuery();
            if(rs.next()){
                int uid = rs.getInt("UId");
                int utype = rs.getInt("UType");
                user = new User(uid,uname,upassword,utype);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con,pstmt,rs);
        }
        return user;
    }

    @Override
    public int addOneUser(String uname, String upassword) {
        String sql = "Insert into User(UName,UPassword,CREATED_By,CREATED_Time) values(?,?,?,Now())";
        Object[] parma = {uname,upassword,uname};
        return executeUpdate(sql,parma);
    }

    @Override
    public int delOneUser(int uid) {
        String sql = "Delete from User where UId = ?";
        Object[] parma = {uid};
        return executeUpdate(sql,parma);
    }

    @Override
    public int editOneUser(User user) {
        String sql = "UPDATE `User` SET UName = ?,Upassword = ? WHERE UId = ?";
        Object[] parma = {user.getUname(),user.getUpassword(),user.getUid()};
        return executeUpdate(sql,parma);
    }
}
